using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace IFXplus.SmartStorage.Utils
{
    public static class Base64Serializer
    {
        #region Serialization
        
        public static string Serialize(object value)
        {
            MemoryStream ws = new MemoryStream();
            BinaryFormatter sf = new BinaryFormatter();
            sf.Serialize(ws, value);
            byte[] bytes = ws.GetBuffer();
            return bytes.Length + ":" + Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
        }

        #endregion

        #region Deserialization

        public static object Deserialize(string base64)
        {
            int p = base64.IndexOf(':');
            int length = Convert.ToInt32(base64.Substring(0, p));
            byte[] data = Convert.FromBase64String(base64.Substring(p + 1));
            MemoryStream rs = new MemoryStream(data, 0, length);
            BinaryFormatter sf = new BinaryFormatter();
            return sf.Deserialize(rs);
        }

        #endregion
    }
}
